package com.rich.dmr.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.util.Log;


public class TCPServer implements ClientHandler.ClientHandlerCallback {
	private final String TAG = "rich---TcpConnect";
	private final int port;
	private ClientListener mListener;
	private List<ClientHandler> clientHandlerList = new ArrayList<>();
	private Context mContext;
	private Handler handler;

	public TCPServer(int port, Context context, Handler handler) {
		this.port = port;
		this.handler = handler;
		mContext = context;
	}

	public boolean start() {
		try {
			ClientListener listener = new ClientListener(port);
			mListener = listener;
			listener.start();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public void stop() {
		if (mListener != null) {
			mListener.exit();
		}

		synchronized (TCPServer.this) {
			for (ClientHandler clientHandler : clientHandlerList) {
				clientHandler.exit();
			}

			clientHandlerList.clear();
		}
	}

	public synchronized void broadcast(String str) {
		for (ClientHandler clientHandler : clientHandlerList) {
			clientHandler.send(str);
		}
	}

	@Override
	public synchronized void onSelfClosed(ClientHandler handler) {
		clientHandlerList.remove(handler);
	}

	@Override
	public void onNewMessageArrived(ClientHandler handler, String msg) {
		Log.d(TAG, "Received-" + handler.getClientInfo() + ":" + msg);
	}

	private class ClientListener extends Thread {
		private ServerSocket server;
		private boolean done = false;

		private ClientListener(int port) throws IOException {
			server = new ServerSocket(port);
			Log.d(TAG,
					"服务器信息：" + server.getInetAddress() + " P:"
							+ server.getLocalPort());
		}

		@Override
		public void run() {
			super.run();

			Log.d(TAG, "服务器准备就绪～");
			// 等待客户端连接
			do {
				// 得到客户端
				Socket client;
				try {
					client = server.accept();
				} catch (IOException e) {
					continue;
				}
				try {
					// 客户端构建异步线程
					ClientHandler clientHandler = new ClientHandler(client,
							TCPServer.this, mContext,handler);
					// 读取数据并打印
					clientHandler.readToPrint();
					// 添加同步处理
					synchronized (TCPServer.this) {
						clientHandlerList.add(clientHandler);
					}
				} catch (IOException e) {
					e.printStackTrace();
					Log.d(TAG, "客户端连接异常：" + e.getMessage());
				}
			} while (!done);

			Log.d(TAG, "服务器已关闭！");
		}

		void exit() {
			done = true;
			try {
				server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
